package com.wangt.biz.socket;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * @author gongtan
 */
@Slf4j
public class TCPClientHandler extends ChannelInboundHandlerAdapter {
    private static String clientName = "客户端1";

    @Override
    public void channelActive(ChannelHandlerContext context) throws Exception {
        log.info("协议==> TCP：客户端（本机）({})与服务器({})连接成功",
            context.channel().localAddress(), context.channel().remoteAddress());
        ByteBuf buf = Unpooled.copiedBuffer(clientName, StandardCharsets.UTF_8);
        context.writeAndFlush(buf);
    }

    @Override
    public void channelRead(ChannelHandlerContext context, Object msg) throws Exception {
        InetSocketAddress socket = (InetSocketAddress) context.channel().remoteAddress();
        String clientIP = socket.getAddress().getHostAddress();
        String clientPort = String.valueOf(socket.getPort());
        log.info("TCP客户端（本机）收到服务端（{}:{}）的数据：{}", clientIP, clientPort, msg);
    }
}
